package cn.kgc.vue.controller;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Dept;
import cn.kgc.vue.service.DeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/4/11
 * @description
 */
@RestController
@RequestMapping("dept")
public class DeptController {


    @Resource
    private DeptService deptService;

    @GetMapping("list")
    @ApiOperation("部门列表")
    public ResponseResult  deptList(){
        List<Dept> list = deptService.list();
        return  ResponseResult.success().data("deptList",list);
    }

    @PostMapping("page")
    @ApiOperation("部门分页数据")
    public ResponseResult  deptPage(@RequestBody QueryCondition<Dept> queryCondition){

        Page<Dept> deptPage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());

        String deptName = queryCondition.getSearchParams().getDeptName();

        LambdaQueryWrapper<Dept> lambda = new QueryWrapper<Dept>().lambda();
        lambda.eq(StringUtils.isNotBlank(deptName),Dept::getDeptName,deptName);

        deptService.page(deptPage,lambda);

        return  ResponseResult.success()
                .data("total",deptPage.getTotal())
                .data("tableData",deptPage.getRecords());
    }

    @PostMapping("addOrUpdate")
    @ApiOperation("部门添加和更新")
    public ResponseResult  addOrUpdateDept(@RequestBody Dept dept){

        String deptName = dept.getDeptName();

        LambdaQueryWrapper<Dept> lambda = new QueryWrapper<Dept>().lambda();
        lambda.eq(Dept::getDeptName,deptName);
        Dept one = deptService.getOne(lambda);
        Integer formId = dept.getId();
        // 判定部门名称是否存在
        if (ObjectUtils.isNotNull(one)){
            Integer DBId = one.getId();
            if (DBId.equals(formId)){
                deptService.saveOrUpdate(dept);
                return ResponseResult.success();
            }
            return  ResponseResult.fail().message("部门名称已存在");
        }

        deptService.saveOrUpdate(dept);
        return  ResponseResult.success();
    }


    @GetMapping("getById/{id}")
    @ApiOperation("根据id获取部门信息")
    public ResponseResult getDeptById(@PathVariable("id") Integer id){

        Dept dept = deptService.getById(id);

        return  ResponseResult.success().data("dept",dept);
    }

    @DeleteMapping("delete/{id}")
    @ApiOperation("根据id删除部门信息")
    public ResponseResult deleteDeptById(@PathVariable("id") Integer id){

        return deptService.deleteDept(id);
    }
}
